package com.xydtech.ecard.ecard.service.impl;

import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.utils.AESEncryptionUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.ecard.config.mapper.EcardApiSysConfigMapper;
import com.xydtech.ecard.custgroup.domain.EcardApiCustomerGroupMerchant;
import com.xydtech.ecard.custgroup.mapper.EcardApiCustomerGroupMerchantMapper;
import com.xydtech.ecard.ecard.domain.*;
import com.xydtech.ecard.ecard.mapper.*;
import com.xydtech.ecard.ecard.service.IEcardApiMerchantInfoService;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.mapper.EcardApiUserMapper;
import com.xydtech.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 电子名片商户信息Service业务层处理
 *
 * @author xydtech
 * @date 2023-07-25
 */
@Service
public class EcardApiMerchantInfoServiceImpl implements IEcardApiMerchantInfoService {
    @Autowired
    private EcardApiUserMapper userMapper;
    @Autowired
    private EcardApiMerchantInfoMapper ecardMerchantInfoMapper;
    @Autowired
    private EcardApiMerchantTaskMapper ecardApiMerchantTaskMapper;
    @Autowired
    private EcardApiMerchantHandoverMapper ecardMerchantHandoverMapper;
    @Autowired
    private EcardApiMerchantReservationTaskMapper ecardApiMerchantReservationTaskMapper;
    @Autowired
    private EcardPriorCreditRecordMapper ecardPriorCreditRecordMapper;
    @Autowired
    private EcardApiSysConfigMapper ecardApiSysConfigMapper;
    @Autowired
    private EcardApiMerchantTaskMapper ecardMerchantTaskMapper;
    @Autowired
    private EcardApiEnterpriseInfoMapper ecardEnterpriseInfoMapper;
    @Autowired
    private EcardApiAgricultureInfoMapper ecardAgricultureInfoMapper;
    @Autowired
    private EcardApiPersonInfoMapper ecardPersonInfoMapper;
    @Autowired
    private EcardApiCustomerGroupMerchantMapper ecardCustomerGroupMerchantMapper;
    @Autowired
    private ISysDeptService sysDeptService;
    /**
     * 查询电子名片商户信息
     *
     * @param id 电子名片商户信息主键
     * @return 电子名片商户信息
     */
    @Override
    public EcardApiMerchantInfo selectEcardMerchantInfoById(Long id, String salt) {
        EcardApiMerchantInfo merchantInfo = ecardMerchantInfoMapper.selectEcardMerchantInfoById(id);
        try {
            if (merchantInfo != null) {
                //数据解密（手机号、身份证号）
                if (!StringUtils.objIsNullOrEmpty(merchantInfo.getPhoneNumber())) {
                    merchantInfo.setPhoneNumber(AESEncryptionUtils.decrypt(merchantInfo.getPhoneNumber(), salt));
                }
            }
            return merchantInfo;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询电子名片商户信息
     * @param id
     * @param creatorId
     * @return
     */
    @Override
    public EcardApiMerchantInfo selectEcardMerchantInfoByIdAndCreatorId(Long id,Long creatorId) {
        return ecardMerchantInfoMapper.selectEcardMerchantInfoByIdAndCreatorId(id,creatorId);
    }

    /**
     * 查询电子名片商户信息列表
     *
     * @param ecardMerchantInfo 电子名片商户信息
     * @return 电子名片商户信息
     */
    @Override
    public List<EcardApiMerchantInfo> getMerchantList(EcardApiMerchantInfo ecardMerchantInfo) {
        return ecardMerchantInfoMapper.getMerchantList(ecardMerchantInfo);
    }

    /**
     * 查询电子名片我的商户信息列表
     *
     * @param ecardMerchantInfo 电子名片商户信息
     * @return 电子名片商户信息
     */
    @Override
    public List<EcardApiMerchantInfo> getMyMerchantInfoList(EcardApiMerchantInfo ecardMerchantInfo, String salt) {
        try {
            //数据加密（手机号、身份证号）
            if (!StringUtils.objIsNullOrEmpty(ecardMerchantInfo.getContactsPhone())) {
                ecardMerchantInfo.setContactsPhone(AESEncryptionUtils.encrypt(ecardMerchantInfo.getContactsPhone(), salt));
            }
            List<EcardApiMerchantInfo> merchantInfoList = ecardMerchantInfoMapper.getMyMerchantInfoList(ecardMerchantInfo);
            if (merchantInfoList.size() > 0) {
                for (EcardApiMerchantInfo merchantInfo : merchantInfoList) {
                    //数据解密（手机号、身份证号）
                    if (!StringUtils.objIsNullOrEmpty(merchantInfo.getContactsPhone())) {
                        merchantInfo.setContactsPhone(AESEncryptionUtils.decrypt(merchantInfo.getContactsPhone(), salt));
                    }
                    if (!StringUtils.objIsNullOrEmpty(merchantInfo.getPhoneNumber())) {
                        merchantInfo.setPhoneNumber(AESEncryptionUtils.decrypt(merchantInfo.getPhoneNumber(), salt));
                    }
                }
            }
            return merchantInfoList;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 保存电子名片商户信息
     *
     * @param ecardMerchantInfo 电子名片商户信息
     * @return 结果
     */
    @Override
    public int addMerchantInfo(EcardApiMerchantInfo ecardMerchantInfo, String salt) {
        try {
            //数据加密（手机号、身份证号）
            if (!StringUtils.objIsNullOrEmpty(ecardMerchantInfo.getPhoneNumber())) {
                ecardMerchantInfo.setPhoneNumber(AESEncryptionUtils.encrypt(ecardMerchantInfo.getPhoneNumber(), salt));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ecardMerchantInfoMapper.addMerchantInfo(ecardMerchantInfo);
    }

    /**
     * 唯一值验证,相同行业、支行、门头名不能重复
     *
     * @date 2023/7/26 14:26
     */
    @Override
    public int validateMerchantInfo(EcardApiMerchantInfo ecardMerchantInfo) {
        return ecardMerchantInfoMapper.validateMerchantInfo(ecardMerchantInfo);
    }

    /**
     * 根据ID修改商户状态
     *
     * @author yjs
     * @date 2023/7/27 10:35
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeMerchantStatus(Long id) {
        //查询是否存在未处理营销任务
        EcardApiMerchantTask merchantTask = ecardApiMerchantTaskMapper.getMerchantTaskByMerchantId(id, "2");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
        if (merchantTask!=null) {
            //存在则更新为已完成
            merchantTask.setTaskSts("1");
            ecardApiMerchantTaskMapper.updateEcardMerchantTask(merchantTask);
        }
        //同步修改行业客户中的状态
        EcardApiCustomerGroupMerchant groupMerchant = new EcardApiCustomerGroupMerchant();
        groupMerchant.setMerchantId(id);
        groupMerchant.setMerchantType("2");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
        List<EcardApiCustomerGroupMerchant> customerGroupMerchantList = ecardCustomerGroupMerchantMapper.selectEcardCustomerGroupMerchantList(groupMerchant);
        if (customerGroupMerchantList.size() > 0) {
            ecardCustomerGroupMerchantMapper.changeIndustrialCustomerStatus(customerGroupMerchantList.get(0).getId());
        }
        return ecardMerchantInfoMapper.changeMerchantStatus(id);
    }

    @Override
    public List<EcardApiMerchantInfo> getMerchantCoordinateList(Long creatorId,Long deptId,Integer industry) {
        return ecardMerchantInfoMapper.getMerchantCoordinateList(creatorId,deptId,industry);
    }

    @Override
    public List<EcardApiMerchantInfo> getAllMerchantCoordinateList(Long creatorId, Long deptId,Integer industry) {
        return ecardMerchantInfoMapper.getAllMerchantCoordinateList(creatorId, deptId,industry);
    }

    /**
     * 个人/商户/企业/新型农业主体/行业客户转交
     * @param merchantHandover
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addMerchantTransferInfo(EcardApiMerchantHandover merchantHandover) {
        //获取接收人的用户信息
        EcardApiUserInfo recipients = userMapper.getUserInfo(merchantHandover.getRecipientId().toString());
        //保存转交记录
        ecardMerchantHandoverMapper.insertEcardMerchantHandover(merchantHandover);
        String merchantType = merchantHandover.getMerchantType();//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
        //查询是否存在未处理营销任务
        EcardApiMerchantTask merchantTask = ecardApiMerchantTaskMapper.getMerchantTaskByMerchantId(merchantHandover.getMerchantId(), merchantType);
        if (merchantTask!=null) {
            //存在则修改营销任务归属人
            merchantTask.setCmRegistId(merchantHandover.getRecipientId());
            ecardApiMerchantTaskMapper.updateEcardMerchantTask(merchantTask);
        }
        //查询是否存在未处理的个人/商户/企业/新型农业主体预约任务
        List<EcardApiMerchantReservationTask> merchantReservationTaskList = ecardApiMerchantReservationTaskMapper.getMerchantReservationTaskByMerchantId(merchantHandover.getMerchantId(), merchantType);
        for(EcardApiMerchantReservationTask merchantReservationTask : merchantReservationTaskList) {
            merchantReservationTask.setCmRegistId(merchantHandover.getRecipientId());
            ecardApiMerchantReservationTaskMapper.updateEcardMerchantReservationTask(merchantReservationTask);
        }
        //查询个人/商户/企业/新型农业主体是否存在正常状态的预授信卡，存在则同步转交
        EcardPriorCreditRecord ecardPriorCreditRecord=new EcardPriorCreditRecord();
        ecardPriorCreditRecord.setAssociationId(merchantHandover.getMerchantId());
        ecardPriorCreditRecord.setSts("1");
        ecardPriorCreditRecord.setCustType(merchantType);//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
        List<EcardPriorCreditRecord> creditRecords = ecardPriorCreditRecordMapper.selectEcardPriorCreditRecordList(ecardPriorCreditRecord);
        for(EcardPriorCreditRecord creditRecord : creditRecords) {
            creditRecord.setUserId(recipients.getUserId());
            ecardPriorCreditRecordMapper.updateEcardPriorCreditRecord(creditRecord);
        }
        int id = 0;
        /**
         * 行业客户关联表同步转交20241128
         * 思路：
         * 1、先转交行业客户关联表中的信息，根据商户类型和商户id转交
         * 2、再转交对应商户信息
         */
        SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(merchantHandover.getRecipientDeptId());
        Long corpId = sysDept.getDeptId();//接收人的法人机构id
        ecardCustomerGroupMerchantMapper.updateCustomerGroupMerchantUserId(merchantType, merchantHandover.getMerchantId(), merchantHandover.getRecipientId(), merchantHandover.getRecipientDeptId(), corpId);
        //商户类型：1-个人，2-商户，3-企业，4-新型农业主体加判断
        if ("1".equals(merchantType)) {//个人
            id = ecardPersonInfoMapper.updatePersonUserId(merchantHandover.getMerchantId(), merchantHandover.getRecipientId(), merchantHandover.getRecipientDeptId());
        }
        if ("2".equals(merchantType)) {//商户
            id = ecardMerchantInfoMapper.updateMerchantUserId(merchantHandover.getMerchantId(), merchantHandover.getRecipientId(), merchantHandover.getRecipientDeptId());
        }
        if ("3".equals(merchantType)) {//企业
            id = ecardEnterpriseInfoMapper.updateEnterpriseUserId(merchantHandover.getMerchantId(), merchantHandover.getRecipientId(), merchantHandover.getRecipientDeptId());
        }
        if ("4".equals(merchantType)) {//新型农业主体
            id = ecardAgricultureInfoMapper.updateAgricultureUserId(merchantHandover.getMerchantId(), merchantHandover.getRecipientId(), merchantHandover.getRecipientDeptId());
        }
        return id;
    }

    /**
     * 查询个人/商户/企业/新型农业主体网格任务总条数接口
     * @param registId
     * @return
     */
    @Override
    public int getMerchantTaskTotalNum(Long registId) {
        return ecardMerchantInfoMapper.getMerchantTaskTotalNum(registId);
    }

    /**
     * 分词查询商户/企业/新型农业主体信息
     * @param licenseName
     * @param merchantType
     * @return
     */
    @Override
    public List<EcardApiMerchantInfo> selectParticipleEcardMerchantInfo(String licenseName, String merchantType, Long registId, Long deptId, String salt) {
        List<EcardApiMerchantInfo> merchantInfoList = ecardMerchantInfoMapper.selectParticipleEcardMerchantInfo(licenseName, merchantType, deptId);
        if (merchantInfoList.size() > 0) {
            for (EcardApiMerchantInfo merchantInfo : merchantInfoList) {
                try {
                    //数据解密（手机号、身份证号）
                    if (!StringUtils.objIsNullOrEmpty(merchantInfo.getPhoneNumber())) {
                        merchantInfo.setPhoneNumber(AESEncryptionUtils.decrypt(merchantInfo.getPhoneNumber(), salt));
                    }
                    if (merchantInfo.getCreatorId().longValue() != registId.longValue()) {
                        merchantInfo.setOneself("1");//是否自己：否
                    } else {
                        merchantInfo.setOneself("0");//是否自己：是
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return merchantInfoList;
    }

}
